package textviewer.main;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class GUIBookShelfBkSelect extends Activity{
	private Config myconfig;
	private FileIO fileio;
	private String SelectedBook;
	private ArrayList<String> path_list;
	private ArrayList<String> cover_list = new ArrayList<String>();
	private ArrayList<BookShelfBkClickListener> bsbcl = new ArrayList<BookShelfBkClickListener>();
	private Utility myutility;
	private String charset="UTF-8";
	private ArrayList<String> pathlist_withoutExt;
	private ArrayList<String> coverlist_withoutExt;
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        Bundle extras = getIntent().getExtras();
        
        if(extras!=null)
        {
        	String tmp_charset=extras.getString("Current_Charset");
        	charset=tmp_charset;
        }
        //Utility.quick_dialog(charset, this);
    	myconfig = new Config(this);
    	fileio = new FileIO();
    	myutility = new Utility();
    	//Bundle extras = getIntent().getExtras();
    	//SelectedBook = extras.getString("SelectedBook");
    	path_list = fileio.scan_folder();
    	// Utility.quick_dialog(String.valueOf(path_list.size()), this);
    	path_list=fileio.filter_folder(path_list);
        cover_list = fileio.scan_img_folder();
        cover_list = fileio.filter_ImgExt(cover_list);
        
    	ScrollView scllview = new ScrollView(this);
    	ScrollView.LayoutParams scllview_param = new ScrollView.LayoutParams(
        		ViewGroup.LayoutParams.FILL_PARENT,
        		ViewGroup.LayoutParams.FILL_PARENT);
    	LinearLayout Llay = new LinearLayout(this);
        LinearLayout.LayoutParams Llay_param = new LinearLayout.LayoutParams(
        		ViewGroup.LayoutParams.FILL_PARENT,
        		ViewGroup.LayoutParams.FILL_PARENT);
        scllview.setBackgroundColor(Color.WHITE);
        scllview.setBackgroundDrawable(myconfig.return_bg());
        Llay.setOrientation(LinearLayout.VERTICAL);
        //Utility.quick_dialog(String.valueOf(path_list.size()), this);

        pathlist_withoutExt = Utility.replace_extension(path_list);
    	coverlist_withoutExt = Utility.replace_extension(cover_list);
    	for(int i=0;i<pathlist_withoutExt.size();i++)
    	{
    		pathlist_withoutExt.set(i,pathlist_withoutExt.get(i).replace(fileio.get_sdcard_dest(), ""));
    	}
    	for(int i=0;i<coverlist_withoutExt.size();i++)
    	{
    		coverlist_withoutExt.set(i,coverlist_withoutExt.get(i).replace(fileio.get_sdcard_dest()+"covers/", ""));
    	}
    	ViewGroup.LayoutParams img_panel_param = new ViewGroup.LayoutParams(100,100);
        
    	for(int i=0;i<path_list.size();i++)
        {
        	LinearLayout tmp_layout = new LinearLayout(this);
            LinearLayout.LayoutParams tmp_layout_param = new LinearLayout.LayoutParams(
            		ViewGroup.LayoutParams.FILL_PARENT,
            		ViewGroup.LayoutParams.WRAP_CONTENT);
        	TextView tmp_txtview = new TextView(this);
        	tmp_txtview.setText(pathlist_withoutExt.get(i));
        	tmp_txtview.setTextColor(Color.BLACK);
        	tmp_layout.setOrientation(LinearLayout.HORIZONTAL);
        	
        	ImageView tmpimg_view = new ImageView(this);
        	tmp_layout.setClickable(true);
        	tmp_layout.setId(i);
        	registerForContextMenu(tmp_layout);
        	tmp_layout.setLongClickable(true);
        	boolean have_cover = false;

        	for(int j=0;j<coverlist_withoutExt.size();j++)
        	{
		        	if(coverlist_withoutExt.get(j).equals(pathlist_withoutExt.get(i)))
		        	{ 
		        		have_cover = true;
		        		BitmapFactory.Options options = new BitmapFactory.Options();
		        		options.inSampleSize = 1;
		        		BitmapDrawable default_cover = new BitmapDrawable(BitmapFactory.decodeFile(this.cover_list.get(j), options));

		        		tmpimg_view.setScaleType(ImageView.ScaleType.CENTER_CROP);
		        		//tmpimg_view.setAdjustViewBounds(true);
		        		//tmpimg_view.setMaxHeight(5);
		        		//tmpimg_view.setMaxWidth(5);
		        		
		        		tmpimg_view.setBackgroundDrawable(default_cover);
		        	}
        	}
        	if(!have_cover)
        	{
        		//BitmapDrawable default_cover = new BitmapDrawable(BitmapFactory.decodeResource(this.getResources(), R.drawable.nocover));
        		//tmpimg_view.setBackgroundDrawable(default_cover);
        		tmpimg_view.setImageResource(R.drawable.nocover);
        	}
        	
        	PanelOnTouchListener potl = new PanelOnTouchListener(tmp_txtview);
        	tmp_layout.setOnTouchListener(potl);
        	tmp_layout.addView(tmpimg_view,img_panel_param);
        	tmp_layout.addView(tmp_txtview);
        	
        	BookShelfBkClickListener bsbkcl = new BookShelfBkClickListener(this,pathlist_withoutExt.get(i),this.path_list.get(i),charset);
        	bsbcl.add(bsbkcl);
        	tmp_layout.setOnClickListener(bsbkcl);
        	Llay.addView(tmp_layout,tmp_layout_param);
        }
    	this.setTitle("Smart Text Viewer - Book Shelf");
        scllview.addView(Llay, Llay_param);
        this.setContentView(scllview, scllview_param);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	ArrayList<String> charset_code = this.myutility.return_charset_code();
        SubMenu submenu_charset = menu.addSubMenu(0, charset_code.size(), 2, "Charset").setIcon(android.R.drawable.ic_menu_view); 
        
        for(int i=0;i<charset_code.size();i++)
        {
     	   submenu_charset.add(0,i ,0,charset_code.get(i));
        }
        SubMenu More_functions = menu.addSubMenu(0, charset_code.size(), 5, "More Functions").setIcon(android.R.drawable.ic_menu_more);
        
        menu.add(0, charset_code.size()+1, 4, "Exit").setIcon(android.R.drawable.ic_menu_close_clear_cancel); 
       
        menu.add(0, charset_code.size()+2, 3, "Setting").setIcon(android.R.drawable.ic_menu_preferences);
        menu.add(0, charset_code.size()+3, 0, "Gather from Internet").setIcon(android.R.drawable.ic_menu_search);
        menu.add(0, charset_code.size()+4, 1, "Add a folder").setIcon(android.R.drawable.ic_menu_edit);
        More_functions.add(0, charset_code.size()+5, 0, "Download file from SDCard");
        More_functions.add(0, charset_code.size()+6, 1, "Refresh the bookshelf");
        return super.onCreateOptionsMenu(menu); 
    	
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) { 
    	ArrayList<String> charset_code = this.myutility.return_charset_code();
    	for(int i = 0;i<charset_code.size();i++)
    	{
    		if(i==item.getItemId())
    		{
    			this.charset=charset_code.get(i);
    			for(int y=0;y<bsbcl.size();y++)
    			{
    				bsbcl.get(y).set_charset(charset);
    			}
    	        Utility.quick_dialog("Charset has changed to "+charset, this);
    			return super.onOptionsItemSelected(item); 
    		}
    	}
    	
    	if(item.getItemId()==charset_code.size())
    	{
    		//Do northing
    	}
    	else if(item.getItemId()==(charset_code.size()+1))
    	{
    		finish();
    	}
    	else if(item.getItemId()==(charset_code.size()+2))
    	{
    		//Utility.quick_dialog("Settings clicked", this);
    		Intent int_ent = new Intent(this, GUIConfig.class);
    		this.startActivity(int_ent);
    		//finish();
    	}
    	else if(item.getItemId()==(charset_code.size()+3))
    	{
    		Intent int_ent = new Intent(this, GUIInternetList.class);
    		this.startActivity(int_ent);
    		//finish();
    	}
    	else if(item.getItemId()==(charset_code.size()+4))
    	{
    		this.showDialog(DIALOG_TEXT_ENTRY);
    	}
    	else if(item.getItemId()==(charset_code.size()+5))
    	{
    		Intent int_ent = new Intent(this, GUIBookSelector.class);
    		this.startActivity(int_ent);
    	}
    	else if(item.getItemId()==(charset_code.size()+6))
    	{
    		this.refresh_me();
    	}

    return super.onOptionsItemSelected(item); 
    } 

    public String get_currCharset()
    {
		return charset;
    }
    private int panel_id_selected=0;
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
    {
 
	    	panel_id_selected=v.getId();
	    	menu.setHeaderTitle(path_list.get(panel_id_selected).replace(fileio.get_sdcard_dest(), ""));
	    	
	    	
	       // Toast.makeText(
	       //         GUIMain.this,
	      //          String.valueOf(panel_id_selected),
	       //         Toast.LENGTH_LONG).show();
	    	menu.add(0, 0, 0, "Open");
	    	menu.add(0, 1, 2, "Delete");
	    	menu.add(0, 2, 1, "Rename");
	    	menu.add(0, 3, 3, "Details");
	    	
    	super.onCreateContextMenu(menu, v, menuInfo);
    }
    @Override 
    public boolean onContextItemSelected(MenuItem item) { 
    	switch(item.getItemId()){
    	case 0: 
    		BookShelfBkClickListener bsbkcl = new BookShelfBkClickListener(this,pathlist_withoutExt.get(panel_id_selected),this.path_list.get(panel_id_selected),charset);
    		bsbkcl.goToChaperPage();
    		break;
    	case 1: 
    		if(FileIO.delete_hole_folder(this.path_list.get(panel_id_selected), this,this))
    		{
    			refresh_me();
    			Utility.quick_dialog("Folder deleted successfully.", this);
    		}
    		//Utility.quick_dialog(this.path_list.get(panel_id_selected), this);
    		break;
    	case 2:
    		this.showDialog(DIALOG_RENAME_ENTRY);
    		break;
    	case 3:
			Intent int_ent = new Intent(this, GUIFileDetail.class);
			int_ent.putExtra("filepath", path_list.get(panel_id_selected));
			this.startActivity(int_ent);
    		break;
    	}
    	return super.onContextItemSelected(item);  
    }
    public void refresh_me()
    {
		Intent int_ent = new Intent(this, GUIBookShelfBkSelect.class);
		int_ent.putExtra("Current_Charset", this.charset);
		this.startActivity(int_ent);
		this.finish();
    }
    private static final int DIALOG_TEXT_ENTRY = 7;
    private static final int DIALOG_RENAME_ENTRY = 8;
    @Override   
    protected Dialog onCreateDialog(int id) {
    	switch(id){
        case DIALOG_RENAME_ENTRY:
        	// This example shows how to add a custom layout to an AlertDialog
        	LayoutInflater factory2 = LayoutInflater.from(this);
        	final EditText search_box2 = new EditText(this);
        	final View textEntryView2 = search_box2;
        	return new AlertDialog.Builder(GUIBookShelfBkSelect.this)
        	//.setIconAttribute(android.R.drawable.)
        	.setTitle("Rename a folder")
        	.setView(textEntryView2)
        	.setPositiveButton("ok", new DialogInterface.OnClickListener() {
        		public void onClick(DialogInterface dialog, int whichButton) {
        				String tmp_str = search_box2.getText().toString();
        				if(!tmp_str.equals(""))
        				{
        					if(fileio.reNameFolderOrFile(GUIBookShelfBkSelect.this.path_list.get(panel_id_selected), tmp_str))
    						{
        						Utility.quick_dialog("Rename is succeed.", GUIBookShelfBkSelect.this);
        						GUIBookShelfBkSelect.this.refresh_me();
    						}
        					else
        					{
        						Utility.quick_dialog("Folder or file with the same name may existed.", GUIBookShelfBkSelect.this);
        					}
        				}
        				else
        				{
        					Utility.quick_dialog("You must enter valid name.", GUIBookShelfBkSelect.this);
        				}
        			} 
        		})
        		.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
        			public void onClick(DialogInterface dialog, int whichButton) {
        				search_box2.setText("");
        				/* User clicked cancel so do some stuff */
        				} 
        			})
        			.create();	
    case DIALOG_TEXT_ENTRY:
    	// This example shows how to add a custom layout to an AlertDialog
    	LayoutInflater factory = LayoutInflater.from(this);
    	final EditText search_box = new EditText(this);
    	final View textEntryView = search_box;
    	return new AlertDialog.Builder(GUIBookShelfBkSelect.this)
    	//.setIconAttribute(android.R.drawable.)
    	.setTitle("Add a folder")
    	.setView(textEntryView)
    	.setPositiveButton("ok", new DialogInterface.OnClickListener() {
    		public void onClick(DialogInterface dialog, int whichButton) {
    				String tmp_encrypted = search_box.getText().toString();
    				if(!tmp_encrypted.equals(""))
    				{
    					if(!fileio.check_Fileexisted(fileio.get_sdcard_root()+tmp_encrypted)&&!fileio.check_Folderexisted(fileio.get_sdcard_root()+tmp_encrypted))
						{
        					fileio.make_folder(fileio.get_sdcard_root()+tmp_encrypted);
        					Utility.quick_dialog("the folder has created successifully", GUIBookShelfBkSelect.this);
        					GUIBookShelfBkSelect.this.refresh_me();
						}
    					else
    					{
    						Utility.quick_dialog("The same name is existed.", GUIBookShelfBkSelect.this);
    					}
    				}
       				else
    				{
    					Utility.quick_dialog("You must enter valid name.", GUIBookShelfBkSelect.this);
    				}

    			} 
    		})
    		.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
    			public void onClick(DialogInterface dialog, int whichButton) {
    				search_box.setText("");
    				/* User clicked cancel so do some stuff */
    				} 
    			})
    			.create();
    	}
    	return null;
    	}
    private boolean activity_restarted=false;
    @Override
    public void onResume() {
    	if(activity_restarted)
    	{
   	 this.refresh_me();
   	activity_restarted=false;
    	}
   	 super.onResume();
    }
    @Override
    public void onPause() {
    	activity_restarted=true;
    	super.onPause();
    }
    @Override  
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    	
    	if(requestCode==0)
    	{	if(resultCode==0)
    	{
    		if(data!=null)
    		{
	    		 Bundle extras = data.getExtras();  
	    		 if(extras!=null)
	    		 this.charset=extras.getString("Current_Charset");
    		}
    		// Utility.quick_dialog("Method called"+charset, this);
    	}
    	}
    	super.onActivityResult(requestCode, resultCode, data);
    }
}
